package com.example.auv_660.autocontrolalgorithm.assistantsensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.example.auv_660.MainActivity;
import com.example.auv_660.util.Constants;

public class SpeedSensor implements SensorEventListener {
    private static SpeedSensor speedSensor;
    private SensorManager sensorManager;
    private Sensor linearAccelerometer;

    private float[] tmpValues = new float[3];
    private double values[] = new double[3];

    private double means[] = new double[3];
    private int number = 0;

    private MainActivity mainActivity = MainActivity.getInstance();

    public synchronized static SpeedSensor getInstance() {
        if (null == speedSensor) {
            speedSensor = new SpeedSensor();
        }
        return speedSensor;
    }

    public double[] getValue()
    {
        return values;
    }

    public SpeedSensor()
    {
        if (mainActivity != null)
        {
            sensorManager = (SensorManager) mainActivity.getSystemService(Context.SENSOR_SERVICE);
        }

        if (sensorManager != null)
        {
            linearAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        }

        register();
    }

    private void register()
    {
        if (sensorManager != null)
        {
            sensorManager.registerListener(this, linearAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    public void unregister()
    {
        if (sensorManager != null)
        {
            sensorManager.unregisterListener(this, linearAccelerometer);
            sensorManager = null;
        }
    }

    private void calculateSpeed()
    {
        values[0] = means[0] / Constants.SPEEDPOINT;
        values[1] = means[1] / Constants.SPEEDPOINT;
        values[2] = means[2] / Constants.SPEEDPOINT;
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION)
        {
            tmpValues = sensorEvent.values;

            if (number == Constants.SPEEDPOINT)
            {
                calculateSpeed();
                number = 0;
                means[0] = 0.0;
                means[1] = 0.0;
                means[2] = 0.0;
            }
            else if (number < Constants.SPEEDPOINT)
            {
                means[0] += Math.abs(tmpValues[0]);
                means[1] += Math.abs(tmpValues[1]);
                means[2] += Math.abs(tmpValues[2]);
                number++;
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }
}
